<script setup lang="ts">
import { ref, reactive } from "vue";
import {
  queryCustomerList,
  addCaseRecord,
  cashRecordList
} from "@/api/customer";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";

defineOptions({
  name: "customer"
});
const currentPage = ref(1);
const pageSize = ref(10); // 添加这行

const pageTotal = ref(0);
let tableData = ref([]);
const type = ref("");
let previewUrl = ref("");
const queryParams = reactive({
  phoneNum: ""
});
//初始化列表
queryListTableData();

//查询列表
function queryListTableData(params?) {
  const _params = {
    pageNo: 1,
    pageSize: 10,
    total: 0,
    ...params
  };
  if (queryParams.phoneNum) {
    _params.phoneNum = queryParams.phoneNum;
  }
  queryCustomerList({ ..._params }).then((res: any) => {
    console.log(res, "res");
    tableData.value = res.data.data;
    pageTotal.value = res.data.total;
  });
}
//筛选
const ruleFormRef = ref<FormInstance>();

const validatesortNum = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入金额"));
  } else {
    if (ruleForm.sortNum !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("sortNum");
    }
    callback();
  }
};
const ruleForm = reactive({
  amount: "",
  giftAmount: "",
  customerId: "",
  remark: ""
});

const rules = reactive<FormRules<typeof ruleForm>>({
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],  
});

//添加
const addRoleDialogVisible = ref(false);
// 在其他 ref 声明附近添加
// 在 handleAdd 函数中添加技能列表初始化
function handleAdd(row,mark) {
  console.log(row, "row");
  addRoleDialogVisible.value = true;
  ruleForm.customerId = row.id;
  type.value = mark;  
}
function addRoleInfo() {
  addCaseRecord({
    giftAmount: ruleForm.giftAmount,
    amount: ruleForm.amount,
    customerId: ruleForm.customerId,
    remark: ruleForm.remark
  })
    .then((res: any) => {
      console.log(res);
      ElMessage({
        type: "success",
        message: res.message
      });
      addRoleDialogVisible.value = false;
      queryListTableData();
    })
    .catch((err: any) => {
      console.log(err);
      ElMessage({
        type: "error",
        message: err.message
      });
    });
}
//查看充值记录
const detailDialogVisible = ref(false);
const detaiInfo = ref([]);
const handleDetail = async row => {
  console.log(row, "row");
  type.value = "detail";
  detailDialogVisible.value = true;
  cashRecordList({
    userId: row.id
  }).then((res: any) => {
    console.log(res);
    detaiInfo.value = res.data;
    detailDialogVisible.value = true;
  });
};
//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("submit!", ruleForm);
      if (type.value == "add") {
        addRoleInfo();
      } 
    } else {
      console.log("error submit!");
    }
  });
};
// 重置页面
const onReset = () => {
  queryParams.phoneNum = "";
  pageTotal.value = 0;
  currentPage.value = 1;
  queryListTableData();
};
//重置添加用户
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryListTableData(val);
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryListTableData(val);
};
function handleClose() {
  console.log("关闭");
  addRoleDialogVisible.value = false;
  detailDialogVisible.value = false;
}
// 头像上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    console.log(response, "response");
    // 使用完整的URL路径
    ruleForm.imageUrl = response.data.dataUrl;
    uploadFile.url = response.data.previewUrl;
    previewUrl.value = uploadFile.url;
    console.log(ruleForm.imageUrl, uploadFile.url, "r");
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>
<template>
  <div class="statement">
    <div class="search">
      <div class="c-input">
        <el-input
          v-model="queryParams.phoneNum"
          clearable
          placeholder="请输入手机号"
        />
      </div>
      <div class="search-btn">
        <el-button type="primary" size="large" @click="queryListTableData"
          >查询</el-button
        >
        <el-button size="large" @click="onReset">重置</el-button>
      </div>
    </div>
    <!-- <div class="add">
      <el-button type="primary" size="large" @click="handleAdd('add')"
        ><el-icon> <Plus /> </el-icon>新增充值</el-button
      >
    </div> -->
    <div class="c-page__bg">
      <el-table :data="tableData">
        <el-table-column prop="username" label="姓名" />
        <el-table-column prop="gender" label="性别" />
        <el-table-column prop="phoneNum" label="手机号" />
        <el-table-column prop="registerTime" label="注册时间" />
        <el-table-column prop="cashRecordCount" label="充值记录数量" />
        <el-table-column prop="amount" label="余额" />
        <el-table-column prop="birthday" label="生日" />
        <el-table-column #default="{ row }" label="操作" width="220">
          <span class="c-text-primary" @click="handleDetail(row)"
            >查看充值记录</span
          >
          <span class="c-text-primary" @click="handleAdd(row, 'add')"
            >新增充值</span
          >
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addRoleDialogVisible"
      title="新增充值"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      > 
        <el-form-item label="金额" prop="amount">
          <el-input
            v-model="ruleForm.amount"
            type="sortNum"
            autocomplete="off"
            placeholder="请输入金额"
          />
        </el-form-item>
        <el-form-item label="赠送金额" prop="giftAmount">
          <el-input
            v-model="ruleForm.giftAmount"
            type="text"
            autocomplete="off"
            placeholder="请输入赠送金额"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="text"
            autocomplete="off"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item
          label="  "
          style="margin-top: 30px"
        >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!--查看充值记录-->
    <el-dialog
      v-model="detailDialogVisible"
      title="查看充值记录"
      width="700"
      :before-close="handleClose"
    >
    <el-table
      :data="detaiInfo"
      style="width: 100%"
      :header-cell-style="{ background: '#F5F7FA', color: '#303133' }">
      <el-table-column prop="amount" label="充值金额" ></el-table-column>
      <el-table-column prop="enterTime" label="充值时间" width="220"></el-table-column>
      <el-table-column prop="giftAmount" label="赠送金额" ></el-table-column>
      <el-table-column prop="operator" label="操作员" ></el-table-column>
      <el-table-column prop="remark" label="备注信息" ></el-table-column>
      </el-table>  
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.statement {
  height: 100%;
  overflow: hidden;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .c-input {
    width: 240px !important;
    margin-bottom: 16px;
    margin-right: 16px;
    --el-border-radius-base: 8px;
    --el-input-focus-border-color: var(--main-color) !important;
    --el-component-size: 40px;
  }

  .search-btn {
    padding-left: 15px;
    .c-btn {
      height: 38px;
      border-radius: 8px;
      box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.c-page__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
.c-drawer-form {
  .c-info__title {
    margin-top: 20px;
    margin-bottom: 20px;
    color: #262626;
    font-size: 16px;
  }
  .el-form-item {
    margin-left: 60px;
    margin-bottonm: 10px;
  }
}
.el-drawer__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 0;
}
.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

// ... 上传图片 ...

.avatar-uploader,
.qrcode-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.required-label::before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

// ... 其他样式 ...
.qrcode-uploader-icon,
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 100px;
}

.qrcode,
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
